package com.cilico.components;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.cilico.R;
import com.cilico.shopcart.ShopCart;
import com.cilico.utils.Utils;
import com.cilico.view.DetailView;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;
import com.cilico.waterfall.Waterfall;

/**
 * 下拉选择框
 * 
 */
public class ComboBox extends TextView implements Component {
	// PopupWindow对象
	private PopupWindow popupWindow = null;
	// 自定义Adapter
	private OptionsAdapter optionsAdapter = null;
	// 展示所有下拉选项的ListView
	private ListView listView = null;
	// 用来处理选中或者删除下拉项消息
	private Handler handler;
	// 上下文
	private BaseView bv_;
	// 下拉箭头位图
	public static Bitmap triBitmap;
	// 控件所在form的action
	public String key_;
	// TextView宽度
	public int width_;
	// TextView高度
	public int height_;
	// 类型
	int type_;
	String text_;
	String url_;
	String[] optionsText_;
	String[] optionsUrl_;
	TextPaint paint_;
	boolean isShowing = false;
	float scale;
	int fontSize_ = 14;
	/**comboBox要动态刷新的控件的名字*/
	String relationName_;

	public ComboBox(Context context, int type, String text, 
			String optionsText, String optionsUrl) {
		super(context);
		bv_ = (BaseView) context;
		text_ = text;
		paint_ = new TextPaint();
		paint_.setTextSize(Utils.getScaledValue(fontSize_));
	    scale = Utils.SCALEDATE_W * Utils.DM_DENSITY;
	    paint_.setTextSize(Utils.getScaledValue(fontSize_));
		
		height_ = Utils.getScaledValue(25);
		try {
			// 创建下拉指示位图
			if (null == triBitmap) {
				triBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.triangle);
			}
			
			// 获取option最大宽度作为宽度
			optionsText_ = optionsText.split("@");
			int optSize = optionsText_.length;
			width_ = (int) paint_.measureText(optionsText_[0]);
			for (int i = 0; i < optSize; i++) {
				if ((int) paint_.measureText(optionsText_[i]) > width_) {
					width_ = (int) paint_.measureText(optionsText_[i]);
				}
			}
			width_ += triBitmap.getWidth() * 2.5;
			
			// 获取当前option链接
			optionsUrl_ = optionsUrl.split("@");
			for (int i = 0; i < optSize; i++) {
				if (optionsText_[i].equals(text)) {
					url_ = optionsUrl_[i];
				}
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
		
		
		// 设置点击事件监听器
		setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				try {
					if (isShowing) {
						hide();
					} else {
						show();
					}
				} catch (Exception e) {
					Utils.printException(e);
				}
			}
			
		});
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		try {
			// 圆角矩形圆角弧度
			int radian = 10;
			paint_.setColor(Color.parseColor("#aad4fd"));
			canvas.drawRoundRect(new RectF(0, 0, width_, height_), radian, radian, paint_);
			paint_.setColor(Color.BLACK);
			// 画label文字
			canvas.drawText(text_, 10, (height_ + fontSize_ * scale) / 2 - 4 , paint_);
			// 画下拉箭头
			float triLeft = (float) (width_ + computeHorizontalScrollOffset() - triBitmap.getWidth() * 1.5);
			float triTop = (height_ + getScrollY() - triBitmap.getHeight()) / 2;
			canvas.drawBitmap(triBitmap, triLeft, triTop, paint_);
		} catch (Exception e) {
			invalidate();
			Utils.printException(e);
		}
	}
	
	/**
	 * PopupWindow显示
	 */
	public void show() {
		popupWindow.showAsDropDown(this);
		isShowing = true;
	}

	/**
	 * PopupWindow消失
	 */
	public void hide() {
		popupWindow.dismiss();
		isShowing = false;
	}
	
	String returnMsg;
	/**
	 * 刷新瀑布流
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2014-2-17下午4:20:22
	 * @param waterfall
	 * @param selIndex
	 */
	private void refulash(final Waterfall waterfall,final int selIndex){
		WaitDialog dlg = BaseView.mid_.waitDialog_;
		dlg.addFgTask(bv_, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) {
				url_ = optionsUrl_[selIndex];
				text_ = optionsText_[selIndex];
				waterfall.cmbNum_ = selIndex;
				waterfall.PAGE_NEXT = 1;//重置累加
				returnMsg = bv_.mid_.hm_.requstData(waterfall,url_,
						String.valueOf(selIndex));
			}

			public void onSuccess(WaitDialog dlg) {
				super.onSuccess(dlg);
				WaitDialog.Task.cancelProgressBar(bv_);
				waterfall.makeData(returnMsg,true);
			}
			
			public void onFailure(WaitDialog dlg) {
				super.onFailure(dlg);
			}

		}, false);
		BaseView.mid_.waitDialog_.setText("正在刷新..");
	}
	
	/**
	 * 初始化PopupWindow
	 */
	private void initPopupWindow() {
        // 初始化Handler,用来处理消息
        handler = new Handler() {
            public void handleMessage(Message message) {
                Bundle data = message.getData();
                switch (message.what) {
                case 1:
                    // 选中下拉项
                    int selIndex = data.getInt("selIndex");
                    // 设置输入框显示值
                    postInvalidate();
    				if (bv_ instanceof DetailView){
    					if (relationName_ != null && 
    							!relationName_.trim().equalsIgnoreCase("")) {
    						for (int i = 0; i < bv_.vWidgetArray_.size(); i++) {
    							Object o = bv_.vWidgetArray_.elementAt(i);
    							if (o instanceof Waterfall){
    								Waterfall waterfall = (Waterfall) o;
									if (waterfall.name_.trim().equalsIgnoreCase(relationName_)) {
										refulash(waterfall, selIndex);
									}
    							}else if (o instanceof ShopCart) {
									ShopCart shopCart = (ShopCart)o;
									if (shopCart.waterfall_.name_.trim().equalsIgnoreCase(relationName_)) {
										refulash(shopCart.waterfall_, selIndex);
									}
								}
    						}
						}
    				}
                    break;
                }
            }
        };
        
		// PopupWindow浮动下拉框布局
		View options = (View) bv_.getLayoutInflater().inflate(R.layout.options, null);
		listView = (ListView) options.findViewById(R.id.list);

		// 设置自定义Adapter
		optionsAdapter = new OptionsAdapter(bv_, handler, optionsText_);
		listView.setAdapter(optionsAdapter);
		popupWindow = new PopupWindow(options, width_, Utils.getScaledValue(100));
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true);
	}

	public class OptionsAdapter extends BaseAdapter {
		private String[] opts;
		private Activity activity;
		private Handler handler;

		public OptionsAdapter(Activity activity, Handler handler, String[] optionsText) {
			this.activity = activity;
			this.handler = handler;
			this.opts = optionsText;
		}

		@Override
		public int getCount() {
			return opts.length;
		}

		@Override
		public Object getItem(int position) {
			return opts[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				// 下拉项布局
				convertView = LayoutInflater.from(activity).inflate(R.layout.option_item, null);
				holder.textView = (TextView) convertView.findViewById(R.id.item_text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.textView.setText(opts[position]);

			// 为下拉框选项文字部分设置事件，最终效果是点击将其文字填充到文本框
			holder.textView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 下拉框消失
                    hide();
					Message msg = new Message();
					Bundle data = new Bundle();
					// 设置选中索引
					data.putInt("selIndex", position);
					msg.setData(data);
					msg.what = 1;
					// 发出消息
					handler.sendMessage(msg);
				}
			});
			if (text_.equals(opts[position])) {
				convertView.setBackgroundColor(Color.parseColor("#a1c0d3"));
			} else {
				convertView.setBackgroundColor(Color.parseColor("#d6ebff"));
			}
			return convertView;
		}
	}

	class ViewHolder {
		TextView textView;
	}

	@Override
	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	@Override
	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	@Override
	public void cleanText() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	@Override
	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return width_;
	}

	@Override
	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return height_;
	}

	@Override
	public void setCssStyle(CssStyle style) {
		// TODO Auto-generated method stub

	}

	@Override
	public View getCmpView() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void releaseResource(View view) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	@Override
	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mould() {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width_, height_);
		setLayoutParams(lp);
		initPopupWindow();
	}

	public String getRelationName() {
		return relationName_;
	}

	public void setRelationName(String relationName_) {
		this.relationName_ = relationName_;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (popupWindow.isShowing()) {
			popupWindow.dismiss();
		}
		return super.onKeyDown(keyCode, event);
	}

}
